﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FzWeb.Models
{
    public class FinanceService
    {
        public Entities db
        {
            get
            {
                if (HttpContext.Current.Session["db"] == null)
                {
                    HttpContext.Current.Session["db"] = new Entities();
                }
                return HttpContext.Current.Session["db"] as FzWeb.Models.Entities;
            }
        }

        /// <summary>
        /// 增加单位预付款
        /// </summary>
        /// <param name="ca"></param>
        public void CreateCompanyAdvances(Company_Advances ca)
        {
            System.Data.Common.DbTransaction tran = null;
            try
            {
                db.Connection.Open();
                tran = db.Connection.BeginTransaction();
                //db.AddToCompany_Advances(ca);
                //修改单位的预付款余额
                ca.Company.AdvancesBalance = (ca.Company.AdvancesBalance==null?0:ca.Company.AdvancesBalance) + ca.CAAmount;
                //发送单位预付款收款消息通知
                Message msg = new Message();
                msg.Type = 0;
                msg.From = 0;
                msg.To = ca.Company.User.UserId;
                msg.Content = "您于"+ca.CADate+"缴纳预付款人民币"+ca.CAAmount+"元，目前贵单位预付款余额为人民币"+ca.Company.AdvancesBalance+"元，请注意核对！";
                msg.SendTime = DateTime.Now;
                msg.Status = 0;
                db.AddToMessage(msg);
                db.SaveChanges();
                tran.Commit();
            }
            catch(Exception ex) 
            {
                if (tran != null)
                    tran.Rollback();
                throw ex;
            }
            finally 
            {
            if (db != null && db.Connection.State != System.Data.ConnectionState.Closed)
                db.Connection.Close();
            }
        }
    }
}
